import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config} from '../../shared/smartadmin.config';
$.fn.modal.Constructor.prototype.enforceFocus =function(){};
declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-bom-project',
	templateUrl: './bom-project.component.html',
	styleUrls:['./bom-project.component.css']
})
export class BomProjectComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			projectName: {
				validators: {
					notEmpty: {
						message: '请输入项目名称'
					},
					stringLength: {
						max: 30,
						message: '项目名称30字以内'
					},
				}
			},
			companyName: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择所属厂区'
					}
				}
			},
			signUnit: {
				validators: {
					notEmpty: {
						message: '请输入签约单位'
					},
					stringLength: {
						max: 30,
						message: '签约单位30字以内'
					},
				}
				
			},
			linkMan: {
				validators: {
					notEmpty: {
						message: '请输入联系人'
					},
					stringLength: {
						max: 10,
						message: '联系人10字以内'
					},
				}
			},
			linkPhone: {
				validators: {
					notEmpty: {
						message: '请输入联系电话'
					},
					integer: {
						message: '请输入数字电话号码'
					}
				}
			},
			address: {
				validators: {
					notEmpty: {
						message: '请输入邮寄地址'
					},
					stringLength: {
						max: 80,
						message: '签邮寄地址80字以内'
					},
				}
				
			},
		}
	}
	selectedCompanyId = ''; //过滤条件-公司ID
	selectedCompanyName = ''; //过滤条件-公司名称
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	searchKey:string = ''; //搜索keyword
	bomProjectFrom:any  = {
		id:null,
		companyId: '',
		companyName: '',
		projectName:'',	
		linkMan:'',			
		linkPhone:'',	
		signUnit:'',	
		address:'',	
		isUpdate:'',
		enterMan:'',
		enterTime:'',
		copyInfo: '', //需要识别得信息
		pmId:'',
		pmName:"",
	}
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	formType = 'new';
	fileToUpload: File = null; //上传文件回调参数
	fileUp: string = '';
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
		});
	}

	ngOnInit() {
		this.load();
		this.initPmSelect2();
	}
	//删除
	delRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http_obj("project/deleteBatch.html",{id:row.id}).subscribe(data=>{
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	//table刷新
    refresh() {
    	this.load();
    }
	//搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
    	this.load();
   	}
	//初始化加载list数据
	load() {
		let tableSearch = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				searchKey:this.searchKey,
				companyName: this.selectedCompanyName,
				companyId:this.selectedCompanyId
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(tableSearch);
		this.jsonApiService.http("project/list.html",reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		});
	}
	// order/countOrderStatus.html111   projectKey:'jy'
	//公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	//新增或者编辑公司选中回调
	addCompanySelected(data) {
		this.bomProjectFrom.companyId = data.companyId||'';
		this.bomProjectFrom.companyName = data.companyName;
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	/*
	 * 新增
	 */
	table_add(modal) {
		// this.modalClose(modal);
		modal.show();
		$('#pmSelect2').val("").trigger('change');
		// $("#bomProjectModal").modal("show")
		this.formType = 'new';
	}
	/*
	 * 编辑
	 */
	editRow(row,_this,modal) {
		modal.show();
		$('#pmSelect2').val(row.pmId).trigger('change');
		// $("#bomProjectModal").modal("show")
		this.formType = 'updata';

		_this.stopPropagation();
		for (let item in this.bomProjectFrom){
			this.bomProjectFrom[item]=row[item];
		}
		$("#bomProjectFrom").data('bootstrapValidator').resetForm();
	}
	/*
	 * 关闭弹窗
	 */
	modalClose(modal) {
		modal.hide();
		// $("#bomProjectModal").modal("hide")
		$("#bomProjectFrom").data('bootstrapValidator').resetForm();
		this.bomProjectFrom.id = '';
		this.bomProjectFrom.projectName = '';
		this.bomProjectFrom.linkPhone = '';
		this.bomProjectFrom.linkMan = '';
		this.bomProjectFrom.address = '';
		this.bomProjectFrom.signUnit = '';
		this.bomProjectFrom.companyName = '';
		this.bomProjectFrom.companyId = '';
		this.bomProjectFrom.copyInfo = ''
		this.bomProjectFrom.pmId = ''
		this.bomProjectFrom.pmName = ''
	}
	/*
	 * form提交
	 */
	userControlSubmit(modal) {
		$('#bomProjectFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#bomProjectFrom').data('bootstrapValidator').isValid();  //验证是否通过
		
		if(isValid){
			var addNewData
			if(this.formType == 'new'){
				this.bomProjectFrom.isUpdate = 0		//新建
				addNewData = {
					projectName: this.bomProjectFrom.projectName,
					linkPhone: this.bomProjectFrom.linkPhone,
					linkMan: this.bomProjectFrom.linkMan,
					address: this.bomProjectFrom.address,
					signUnit: this.bomProjectFrom.signUnit,
					companyName: this.bomProjectFrom.companyName,
					companyId: this.bomProjectFrom.companyId,
					isUpdate: 0, //新增
					pmId:this.bomProjectFrom.pmId,
					pmName:this.bomProjectFrom.pmName
				}

			}else if(this.formType == 'updata'){
				this.bomProjectFrom.isUpdate = 1		//编辑
				addNewData = {
					id: this.bomProjectFrom.id,
					projectName: this.bomProjectFrom.projectName,
					linkPhone: this.bomProjectFrom.linkPhone,
					linkMan: this.bomProjectFrom.linkMan,
					address: this.bomProjectFrom.address,
					signUnit: this.bomProjectFrom.signUnit,
					companyName: this.bomProjectFrom.companyName,
					companyId: this.bomProjectFrom.companyId,
					isUpdate: 1, //编辑
					enterMan: this.bomProjectFrom.enterMan,
					enterTime: this.bomProjectFrom.enterTime,
					pmId:this.bomProjectFrom.pmId,
					pmName:this.bomProjectFrom.pmName
				}
			}
			this.jsonApiService.http_obj("project/updateProject.html",addNewData).subscribe(data=> {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
					this.modalClose(modal);
				}
			})
		}
	}

	// 显示导入的弹框
	showImportModal(modal) {
		modal.show();
		// $("#weightModal").modal("show")
	}
	// 关闭导入的弹框
	cancelUp(val) {
		val.hide();
		// $("#weightModal").modal("hide")
		this.fileToUpload = null;
	}
	// 清空input type=file输入框的值
	clearFile() {
		this.fileUp = '';
	}
	//下载模板
	load_module() {
		var elemIF = document.createElement("iframe");
		elemIF.src = config.BaseURL + 'resources/template/project-Template.xlsx';
		elemIF.style.display = "none";
		document.body.appendChild(elemIF);
	}
	//文件上传change回调
	fileChange(files: FileList) {
		this.fileToUpload = files.item(0);
		const isEXCEL = this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || this.fileToUpload.type === "application/vnd.ms-excel";
		if (!isEXCEL) {
			this.jsonApiService.message('上传文件只能是 excel格式!');
			this.fileToUpload = null;
			return;
		}
	}
	//导入submit
	submitData(val) {
		let postParam = new FormData();
		postParam.append('file', this.fileToUpload);
		if (!this.fileToUpload) {
			this.jsonApiService.message('请上传文件')
			return false;
		}
		this.jsonApiService.form_http("project/upload.html", postParam).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				val.hide();
				// $("#weightModal").modal("hide")
				this.fileToUpload = null;
				this.load();
			}
		})
	}




	//识别粘贴过来的信息  正则区分开来
	
	copyInfoClick(){
		if(!this.bomProjectFrom.copyInfo){
			this.jsonApiService.message('暂无内容可识别');
		}
		var info;var strArr=[];

		info = this.bomProjectFrom.copyInfo;
		var breaks = /<br>(\r\n|\n|\r)/gm;

		if(info.indexOf(',') != -1 || info.indexOf('，') != -1){
			info = info.replace(/,|，/g, " ");
		}else if(info.indexOf('.') != -1 || info.indexOf('。') != -1){
			info = info.replace(/.|。/g, " ");
		}else if(info.indexOf(';') != -1 || info.indexOf('；') != -1){
			info = info.replace(/;|；/g, " ");
		}else if(info.indexOf('、') != -1){
			info = info.replace(/、/g, " ");
		}else if(info.indexOf('？') != -1 || info.indexOf('?') != -1){
			info = info.replace(/\?|？/g, " ");
		}else if(info.indexOf('+') != -1 || info.indexOf('=') != -1 || info.indexOf('*') != -1 ){
			info = info.replace(/\+|\=|\*/g, " ");
		}else if(info.indexOf('↵') != -1){
			info = info.replace(/↵/ig, " ")
		}
		//将一个或多个空格转换成一个空格
		info = info.replace(/&nbsp;/ig, " ").replace(/	/g, " ").replace(/[\r\n]/g," ").replace(/\s+/ig," ");
		//以空格为分割点分割成数组
		strArr = info.split(" ");
		
		var regPhone1 = /^1(3|4|5|6|7|8|9)\d{9}$/;
		var regPhone2 = /([0-9]{3,4}-)?[0-9]{7,8}/;
		var regAddress = /([^省]+省|.+自治区|[^市]+市)([^自治州]+自治州|[^市]+市|[^盟]+盟|[^地区]+地区|.+区划)([^市]+市|[^县]+县|[^旗]+旗|.+区)/;
		var regNum=/\d/; //是否包含数字

		var addressArr = ['省',"市","县","区","乡","镇","州","村","工业园"];

		//先给数组排序  数组从小到大排序
		var strArr1 = strArr.sort(function(a, b) {
			if(a.length > b.length){
				return 1;
			}
			if(a.length < b.length){
				return -1;
			}
			return
		})


		//先给数组排序  数组大到小排序
		var strArr2 = JSON.parse(JSON.stringify(strArr1)).reverse();

		//拿到的数组进行遍历 取出其中得姓名，电话   姓名是数据从大到小的排序中  最后一个符合条件替换前一个
		for(var i=0;i<strArr2.length;i++){
			if(strArr2[i].length > 1 && strArr2[i].length < 5 && strArr2[i].indexOf('地址') == -1 && !regNum.test(strArr2[i])){
				// console.log('11111111')
				this.bomProjectFrom.linkMan = strArr2[i];
				continue;
			}else if(regPhone1.test(strArr2[i]) || regPhone2.test(strArr2[i])){
				// console.log('22222222222')
				this.bomProjectFrom.linkPhone = strArr2[i]

			}
		}
		//拿到的数组进行遍历 取出其中地址   地址是数据从小到大的排序中  最后一个符合条件替换前一个
		for(var i=0;i<strArr1.length;i++){
			if(strArr1[i].length > 4){
				// console.log('3333333')
				var k =0;
				for(var j=0;j<addressArr.length;j++){
					++k
					if(strArr1[i].indexOf(addressArr[j]) != -1 && strArr1[i].indexOf(addressArr[j+k]) != -1){
						this.bomProjectFrom.address = strArr1[i];
						break;
					}
					
				}
				
			}else if(regAddress.test(strArr1[i]) && strArr1[i].length > 4){
				// console.log('3333333')
				this.bomProjectFrom.address = strArr1[i]
			}
		}

	}
	clearInfo(){
		this.bomProjectFrom.copyInfo = '';
	}

	//复用信息
	multiplexRow(row,_this,modal){
		modal.show();
		// $("#bomProjectModal").modal("show")
		this.formType = 'new';

		_this.stopPropagation();
		for (let item in this.bomProjectFrom){
			this.bomProjectFrom[item]=row[item];
		}

		this.bomProjectFrom.id = '';
		this.bomProjectFrom.companyId = '';
		this.bomProjectFrom.companyName = '';

		$("#bomProjectFrom").data('bootstrapValidator').resetForm();
	}
	// 初始化项目经理的select2
	initPmSelect2(){
		let that = this;
		this.jsonApiService.http("user/getUserList.html",null).subscribe(data=> {
			if(data.success){
				var userList = data.data;
				var selectdata = [];
				for(var i = 0 ; i < userList.length ; i++) {
					var obj = {
						id:userList[i].id,
						text:userList[i].name,
					}
					selectdata[i] = obj;
				}
				System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
					System.import('assets/js/select2-zh-CN.js').then(()=>{
						$("#pmSelect2").select2({
							language : "zh-CN",
							placeholder :"请选择",
							allowClear : true,
							data : selectdata,//为Select添加数据
							templateResult: this.formatRepo
						}).on ("select2:select", function (e){
								var data = e.params.data;
								that.bomProjectFrom.pmId = data.id
								that.bomProjectFrom.pmName = data.text
						});
					})
				})
			}
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	delpmSelect() {
		this.bomProjectFrom.pmId = ""
		this.bomProjectFrom.pmName = ""
        //采用简单粗暴的方法清除;官方推荐的方法失效
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#pmSelect2').val("");
        $("#select2-pmSelect2-container").empty();
        $("#select2-pmSelect2-container").attr("title", "");
        $("#select2-pmSelect2-container").prepend(str);
    }
}